<?php
/**
 * Created by PhpStorm.
 * User: zjw
 * Date: 2018/10/19
 * Time: 下午5:53
 */

namespace api\modules\v1\controllers;


use common\models\Activity;
use common\models\Coupon;
use common\models\CouponCategory;
use common\models\UserCoupon;
use yii;

class UserCouponController extends RestController
{
    public $modelClass = 'common\models\coupon';

    /**
     * 我的优惠券
     * @return array
     */
    public function actionIndex()
    {
        $couponCategoryList = CouponCategory::getCollection()->find(['like','local_mark_id','cuxiao'],'mark_id')->toArray();
        $tmp=[];
        foreach($couponCategoryList as $couponCategory){
            $tmp[]=$couponCategory['mark_id'];
        }
        $userid=intval(Yii::$app->user->id);
//      $userid=4;
        $coupons = UserCoupon::getCollection()->find(['user_id'=>$userid,'mark_id'=>$tmp])->toArray();
        if(count($coupons)>0){
            $result=[];
            foreach($coupons as $coupon){
                $result[]=Coupon::getCollection()->findOne(['catalog_mark_id'=>$coupon['mark_id']]);
            }
            return ['code' => 1, 'message' => '领券列表','data'=>$result];
        }
        return ['code' => 0, 'message' => '未领过券'];

    }

    public function actionMycoupons(){
        $activity_id=Yii::$app->request->post("activity_id");
        if(empty($activity_id)){
            return ['code' => -1, 'message' => '缺少参数'];
        }
        $activity = Activity::findOne($activity_id);
        if(time()<strtotime($activity->start_time) || time()>strtotime($activity->end_time)){
            return ['code' => -1, 'message' => '不在活动期间或者活动已下架'];
        }
        //我的券
        $couponCategoryList = CouponCategory::getCollection()->findOne(['local_mark_id'=>'tuangou_'.$activity_id]);
//        $tmp=[];
//        foreach($couponCategoryList as $couponCategory){
//            $tmp[]=$couponCategory['mark_id'];
//        }
        $local_mark_id = $couponCategoryList['mark_id'];
        $image = $couponCategoryList['image'];
        $userid=intval(Yii::$app->user->id);
//      $userid=4;
        $coupons = UserCoupon::getCollection()->find(['user_id'=>$userid,'mark_id'=>$local_mark_id])->toArray();
        if(count($coupons)>0){
            $result=[];
            foreach($coupons as $coupon){
                $c = Coupon::getCollection()->findOne(['catalog_mark_id'=>$coupon['mark_id']]);
                $c['image']=$image;
                $c['desc']=json_decode($c['desc']);
                $result[]=$c;
            }

            return ['code' => 1, 'message' => '领券列表','data'=>$result];
        }
        return ['code' => 0, 'message' => '未领过券'];
    }
}
